home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Wed, 24 Jan 96 20:50:54 GMT
- Organization: none
- Distribution: world
- Message-ID: <822516654snz@genesis.demon.co.uk>
- References: <AAQgE1nWVS@csg.spb.su>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <AAQgE1nWVS@csg.spb.su>
- alex@csg.spb.su "Alexander N. Pryguichev" writes:
-
- >There is well known solution:
- >
- >Boolean IsPowerOfTwo(unsigned long x)
- >{ long y;
- > y = x & 0x55555555; y += (x >> 1) & 0x55555555;
- > x = y & 0x33333333; x += (y >> 2) & 0x33333333;
- > y = x & 0x0F0F0F0F; y += (x >> 4) & 0x0F0F0F0F;
- > x = y & 0x00FF00FF; x += (y >> 8) & 0x00FF00FF;
- > y = x & 0x0000FFFF; y += (x >>16) & 0x0000FFFF;
-
- That is a well known method for counting the number of 1 bits in a 32 bit
- value. However it isn't used for determining whether a value is a power of 2
- since, as has been posted, a much better approach exists.
-
- > return y == 1;
- >}
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-